<template>
	<view class="coupon-block">
		<template v-if="lst.length>0">
			<block v-for='(item,index) in lst' :key="index">
				<item :itemData='item' @itemClick='itemClick'></item>
			</block>
		</template>
		<template v-if="lst.length==0">
			<view class="no-emty">暂无优惠券</view>
		</template>
	</view>
</template>

<script>
	import item from '@/pages/coupon/components/item.vue'
	export default {
		components: {
			item
		},
		onShow() {
			this.init()
		},
		data() {
			return {
				lst: [],
			}
		},
		methods: {
			init() {
				this.$http('coupon.getCouponList').then(res => {
					console.log('res', res)
					if (res.code == 200) {
						this.lst = res.data.list
					}
				})
			},
			itemClick(item) {
				//立即购买
				// console.log('item', item)
				this.createCouponOrder(item)
			},
			createCouponOrder(item) {
				this.$http('coupon.buyCoupon', {
					token: this.$tools.getToken(),
					count: 1,
					id: item.id
				}).then(res => {
					if (res.code == 200) {
						this.payFun(res.data.data.order_number)
					} else {
						this.$tools.showMsg(res.msg)
					}
				})
			},
			payFun(orderNumber) {
				this.$http('coupon.payCoupon', {
					token: this.$tools.getToken(),
					order_number: orderNumber
				}).then(res => {
					if (res.code == 200) {
						var AtimeStamp = res.data.timeStamp;
						var AnonceStr = res.data.nonceStr;
						var Apackage = res.data.package;
						var ApaySign = res.data.paySign;
						wx.requestPayment({
							'timeStamp': AtimeStamp,
							'nonceStr': AnonceStr,
							'package': Apackage,
							'signType': 'MD5',
							'paySign': ApaySign,
							'success': function(res) {
								uni.showToast({
									title: '购买成功',
									icon: "none"
								})
								
							},
							'fail': function(res) {
								uni.showToast({
									title: '取消支付',
									icon: "none"
								})
							},
							'complete': function(res) {}
						})
					}
				})
			}

		}
	}
</script>

<style lang="scss" scoped>
	.coupon-block {

		padding: 0 32rpx;
	}

	.no-emty {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 30rpx;
		font-size: 26rpx;color: #999;
	}
</style>
